<template>
  <div class="app-container">
    <el-form :model="queryParams"
             ref="queryForm"
             :inline="true"
             label-width="120px">
      <el-form-item label="名称"
                    prop="name">  
        <el-input v-model="queryParams.name"
                  placeholder="请输入名称"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品名称"
                    prop="shopGoodsId"
                    label-width="70px">
        <el-input v-model="queryParams.shopGoodsId"
                  placeholder="请点击选择商品"
                  class="hover-style" />
      </el-form-item>
      <el-form-item label="是否展示"
                    prop="isShow">
        <el-select v-model="queryParams.isShow"
                   placeholder="请选择是否展示">
          <el-option v-for="dict in isShowOptions"
                     :key="dict.dictValue"
                     :label="dict.dictLabel"
                     :value="dict.dictValue"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="门店id" prop="shopId">
        <el-input
          v-model="queryParams.shopId"
          placeholder="请输入门店id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="广告位置" prop="adPlace">
        <el-input
          v-model="queryParams.adPlace"
          placeholder="请输入广告位置"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="广告位置">
        <el-select v-model="queryParams.adPlace"
                   placeholder="请选择广告位置">
          <el-option v-for="dict in adPlaceOptions"
                     :key="dict.dictValue"
                     :label="dict.dictLabel"
                     :value="dict.dictValue"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   icon="el-icon-search"
                   size="mini"
                   @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh"
                   size="mini"
                   @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10"
            class="mb8">
      <el-col :span="1.5">
        <el-button type="primary"
                   icon="el-icon-plus"
                   size="mini"
                   @click="handleAdd"
                   v-hasPermi="['advert:advertPlace:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success"
                   icon="el-icon-edit"
                   size="mini"
                   :disabled="single"
                   @click="handleUpdate"
                   v-hasPermi="['advert:advertPlace:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger"
                   icon="el-icon-delete"
                   size="mini"
                   :disabled="multiple"
                   @click="handleDelete"
                   v-hasPermi="['advert:advertPlace:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning"
                   icon="el-icon-download"
                   size="mini"
                   @click="handleExport"
                   v-hasPermi="['advert:advertPlace:export']">导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading"
              border
              stripe
              :data="advertPlaceList"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection"
                       width="55"
                       align="center" />
      <!-- <el-table-column label="唯一ID" align="center" prop="id" />
      <el-table-column label="是否有效" align="center" prop="isActive" /> -->
      <el-table-column label="名称"
                       align="center"
                       prop="name" />
      <el-table-column label="广告位置"
                       align="center"
                       prop="adPlace"
                       :formatter="adPlaceFormat" />
      <el-table-column label="广告图片"
                       align="center"
                       prop="picUrl">
        <template slot-scope="scope">
          <img v-if="scope.row.picUrl"
               :src="scope.row.picUrl"
               alt=""
               width="100%"
               height="100%">
        </template>
      </el-table-column>
      <el-table-column label="跳转url"
                       align="center"
                       prop="toUrl" />
      <el-table-column label="小程序跳转url"
                       align="center"
                       prop="toAppUrl" />
      <el-table-column label="小程序id"
                       align="center"
                       prop="appid" />
      <el-table-column label="商品名称"
                       align="center"
                       prop="goodsName" />
      <el-table-column label="商品主图"
                       align="center"
                       prop="goodsImg">
        <template slot-scope="scope">
          <img v-if="scope.row.goodsImg"
               :src="scope.row.goodsImg"
               alt=""
               width="100%"
               height="100%">
        </template>
      </el-table-column>
      <el-table-column label="是否展示"
                       align="center"
                       prop="isShow"
                       :formatter="isShowFormat" />
      <el-table-column label="排序"
                       align="center"
                       prop="orderId" />
      <!-- <el-table-column label="一级销区" align="center" prop="rp02" />
      <el-table-column label="一级销区名称" align="center" prop="rp02name" />
      <el-table-column label="二级销区" align="center" prop="rp03" />
      <el-table-column label="二级销区名称" align="center" prop="rp03name" /> -->
      <!-- <el-table-column label="门店id" align="center" prop="shopId" /> -->
      <el-table-column label="广告内容"
                       align="center"
                       prop="adContent" />
      <el-table-column label="广告占比"
                       align="center"
                       prop="adPercent" />
      <!-- <el-table-column label="是否仅员工可见" align="center" :formatter="isNeedHnFormat" prop="isNeedHn" /> -->
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作"
                       fixed="right"
                       align="center"
                       class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
                     v-hasPermi="['advert:advertPlace:edit']">修改</el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-delete"
                     @click="handleDelete(scope.row)"
                     v-hasPermi="['advert:advertPlace:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList" />

    <!-- 添加或修改零售云广告位对话框 -->
    <el-dialog :title="title"
               :visible.sync="open"
               width="90%"
               append-to-body
               center
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form ref="form"
               :model="form"
               :rules="rules"
               label-width="100px">
        <el-row>
          <el-col :span="18">
            <el-form-item label="名称"
                          prop="name">
              <el-input v-model="form.name"
                        placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="广告位置"
                          prop="adPlace">
              <el-select v-model="form.adPlace"
                         placeholder="请选择广告位置">
                <el-option v-for="dict in adPlaceOptions"
                           :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="广告图片"
                          prop="picUrl">
              <el-upload :action="imageUploader.action"
                         :headers="imageUploader.headers"
                         :on-success="setFormImageUrl"
                         list-type="picture-card"
                         :file-list="imageUploader.fileList">
                <i slot="default"
                   class="el-icon-plus"></i>
                <div slot="file"
                     slot-scope="{file}">
                  <img class="el-upload-list__item-thumbnail"
                       :src="file.url"
                       alt="">
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview"
                          @click="setFormImagePreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span class="el-upload-list__item-delete"
                          @click="removeFormImageUrl(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
              <el-dialog :visible.sync="imageUploader.isShowPreview">
                <img width="100%"
                     :src="imageUploader.previewUrl"
                     alt="">
              </el-dialog>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="跳转url"
                          prop="toUrl">
              <el-input v-model="form.toUrl"
                        placeholder="请输入跳转url" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="小程序跳转url"
                          prop="toAppUrl">
              <el-input v-model="form.toAppUrl"
                        placeholder="请输入小程序跳转url" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="小程序id"
                          prop="appid">
              <el-input v-model="form.appid"
                        placeholder="请输入小程序id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品"
                          prop="goodsName">
              <el-input v-model="form.goodsName"
                        placeholder="请点击右侧按钮选择商品"
                        @clear="clearSelectedGoods"
                        clearable
                        class="input-with-select">
                <el-button v-on:click.native="openProductSelector()"
                           slot="append"
                           icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否展示"
                          prop="isShow">
              <el-select v-model="form.isShow"
                         placeholder="请选择是否展示">
                <el-option v-for="dict in isShowOptions"
                           :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="排序"
                          prop="orderId">
              <el-input v-model="form.orderId"
                        placeholder="请输入排序" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="一级销区" prop="rp02">
              <el-input v-model="form.rp02" placeholder="请输入一级销区" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="一级销区名称" prop="rp02name">
              <el-input v-model="form.rp02name" placeholder="请输入一级销区名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="二级销区" prop="rp03">
              <el-input v-model="form.rp03" placeholder="请输入二级销区" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="二级销区名称" prop="rp03name">
              <el-input v-model="form.rp03name" placeholder="请输入二级销区名称" />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="6">
            <el-form-item label="门店id" prop="shopId">
              <el-input v-model="form.shopId" placeholder="请输入门店id" />
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="广告内容"
                          prop="adContent">
              <el-input v-model="form.adContent"
                        placeholder="请输入广告内容" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="广告占比"
                          prop="adPercent">
              <el-input v-model="form.adPercent"
                        placeholder="请输入广告占比" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="员工可见" prop="isNeedHn">
              <el-select v-model="form.isNeedHn" placeholder="是否仅员工可见" clearable size="small">
                <el-option
                  v-for="dict in isNeedHnOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择商品信息 -->
    <el-dialog fullscreen
               append-to-body
               center
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               title="请选择1条商品"
               :visible.sync="isSelectProduct"
               :before-close="closeProductSelector">
      <product-selector isComponent="true"
                        @onSelect="onSelect"
                        @onCancel="closeProductSelector"></product-selector>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="settingDeptUser">确 定</el-button>
        <el-button @click="closeProductSelector">取 消</el-button>
      </div> -->
    </el-dialog>
  </div>
</template>

<script>
import {
  listAdvertPlace,
  getAdvertPlace,
  delAdvertPlace,
  addAdvertPlace,
  updateAdvertPlace,
  exportAdvertPlace,
} from "@/api/advert/advertPlace";
import ProductSelector from "@/components/ProductSelector";

export default {
  name: "AdvertPlace",
  components: { ProductSelector },
  data() {
    return {
      isSelectProduct: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 零售云广告位表格数据
      advertPlaceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 广告位置字典
      adPlaceOptions: [],
      // 是否仅员工可见字典
      isNeedHnOptions: [],
      // 是否展示字典
      isShowOptions: [],
      // 总店id
      zdIdOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        isActive: undefined,
        name: undefined,
        shopGoodsId: undefined,
        isShow: undefined,
        shopId: undefined,
        adPlace: undefined,
      },
      selectedList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        adPlace: [
          { required: true, message: "请选择广告位置", trigger: "blur" },
        ],
        isShow: [
          { required: true, message: "请选择是否展示", trigger: "blur" },
        ],
        orderId: [{ required: true, message: "请输入排序", trigger: "blur" }],
      },
      imageUploader: {
        action: process.env.VUE_APP_BASE_API + "/common/upload/news",
        headers: {
          Authorization: "Bearer " + this.$store.state.user.token,
          lesseeId: this.$store.state.user.lesseeid,
        },
        fileList: [],
        isShowPreview: false,
        previewUrl: "",
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("SHOP_ADVERT_PLACE").then((response) => {
      this.adPlaceOptions = response.data;
    });
    this.getDicts("sys_yes_no").then((response) => {
      this.isShowOptions = response.data;
      if (this.isShowOptions.length > 0) {
        this.isShowOptions.forEach(function (item) {
          if (item.dictValue == "Y") {
            item.dictValue = 1;
          } else {
            item.dictValue = 0;
          }
        });
        console.log("this.isShowOptions:");
        console.log(this.isShowOptions);
      }
    });
    this.getDicts("sys_yes_no").then((response) => {
      this.isNeedHnOptions = response.data;
      if (this.isNeedHnOptions.length > 0) {
        this.isNeedHnOptions.forEach(function (item) {
          if (item.dictValue == "Y") {
            item.dictValue = 1;
          } else {
            item.dictValue = 0;
          }
        });
      }
    });
    this.getDicts("HN_STAR_DESIGN").then((response) => {
      this.zdIdOptions = response.data;
    });
  },
  methods: {
    clearSelectedGoods() {
      this.selectProducts = [];
      this.queryParams.shopGoodsId = "";
      this.form.shopGoodsId = "";
      this.form.goodsName = "";
    },
    /** 查询零售云广告位列表 */
    getList() {
      this.loading = true;
      const arr = [];
      listAdvertPlace(this.queryParams).then((response) => {
        if (response.rows) {
          response.rows.forEach((item) => {
            arr.push(this.__format(item));
          });
        }
        this.advertPlaceList = arr;
        this.total = response.total;
        this.loading = false;
      });
    },
    __format(item) {
      return {
        id: item.id,
        shopGoodsId: item.shopGoodsId || "",
        isActive: item.isActive,
        name: item.name,
        picUrl: item.picUrl || "",
        isShow: item.isShow,
        orderId: item.orderId,
        adPlace: item.adPlace,
        toUrl: item.toUrl,
        toAppUrl: item.toAppUrl,
        appid: item.appid,
        adContent: item.adContent,
        adPercent: item.adPercent,
        goodsImg:
          item.shopGoods && item.shopGoods.goodsImg
            ? item.shopGoods.goodsImg
            : "",
        goodsName:
          item.shopGoods && item.shopGoods.goodsName
            ? item.shopGoods.goodsName
            : "",
      };
    },
    onSelect(selectProducts) {
      if (!selectProducts || selectProducts.length === 0) return;
      const product = selectProducts[0];
      if (this.shopGoodsId === product.id) return;
      this.queryParams.shopGoodsId = "";
      this.form.shopGoodsId = product.id;
      this.form.goodsName = product.goodsName;
    },
    settingDeptUser() {
      const that = this;
      if (that.selectedList.length > 0) {
        that.form.code = that.selectedList[0].userId;
        that.form.name = that.selectedList[0].userName;
        that.isSelectProduct = false;
      }
    },
    openProductSelector() {
      const that = this;
      that.selectedList = [];
      that.isSelectProduct = true;
    },
    closeProductSelector() {
      this.isSelectProduct = false;
    },
    setSelectedList(item, val) {
      let findIndex = this.selectedList.findIndex(function (obj) {
        return (
          (obj.userId && obj.userId == item.userId) ||
          (!obj.userId && obj.id == item.id && obj.label == item.label)
        );
      });
      if (val) {
        if (findIndex == -1) {
          this.selectedList.push(item);
        }
      } else {
        this.selectedList.splice(findIndex, 1);
      }
    },
    delSelectedList(item) {
      let findIndex = this.selectedList.findIndex(function (obj) {
        return (
          (obj.userId && obj.userId == item.userId) ||
          (!obj.userId && obj.id == item.id && obj.label == item.label)
        );
      });
      if (findIndex > -1) {
        this.selectedList.splice(findIndex, 1);
      }
    },
    setFormImageUrl(response, file, fileList) {
      this.imageUploader.fileList = [file];
      this.form.picUrl = response.url;
    },
    setFormImagePreview(file) {
      this.imageUploader.isShowPreview = !this.imageUploader.isShowPreview;
      this.imageUploader.previewUrl = file.url;
    },
    removeFormImageUrl(file) {
      console.log("file=", file);
      console.log("fileList=", this.imageUploader.fileList);
      this.imageUploader.previewUrl = "";
      this.form.picUrl = "";
      let index = this.imageUploader.fileList.findIndex((obj) => obj == file);
      if (index > -1) {
        this.imageUploader.fileList.splice(index, 1);
      }
    },
    // 总店ID字典翻译
    zdIdFormat(row, column) {
      return this.selectDictLabel(this.zdIdOptions, row.zdId);
    },
    // 广告位置字典翻译
    adPlaceFormat(row, column) {
      return this.selectDictLabel(this.adPlaceOptions, row.adPlace);
    },
    // 是否展示字典翻译
    isShowFormat(row, column) {
      return this.selectDictLabel(this.isShowOptions, row.isShow);
    },
    // 是否仅员工可见字典翻译
    isNeedHnFormat(row, column) {
      return this.selectDictLabel(this.isNeedHnOptions, row.isNeedHn);
    },
    gitADPlace(adPlace) {
      let ADPlaceName = "";
      const that = this;
      for (let i in that.adPlaceOptions) {
        if (that.adPlaceOptions[i].dictValue == adPlace) {
          ADPlaceName = that.adPlaceOptions[i].dictLabel;
          break;
        }
      }
      return ADPlaceName;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        createBy: undefined,
        createTime: undefined,
        updateTime: undefined,
        updateBy: undefined,
        isActive: undefined,
        lesseeId: undefined,
        name: undefined,
        picUrl: undefined,
        toUrl: undefined,
        toAppUrl: undefined,
        shopGoodsId: undefined,
        goodsName: undefined,
        isShow: undefined,
        orderId: undefined,
        rp02: undefined,
        rp02name: undefined,
        rp03: undefined,
        rp03name: undefined,
        shopId: undefined,
        adPlace: undefined,
        adContent: undefined,
        adPercent: undefined,
        appid: undefined,
        isNeedHn: undefined,
        remark: undefined,
      };
      this.imageUploader.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.adPlace = "";
      this.reset();
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.isShow = this.isShowOptions[0].dictValue;
      this.form.isNeedHn = this.isNeedHnOptions[1].dictValue;
      this.form.zdId = this.zdIdOptions[0].dictValue;
      this.title = "添加零售云广告位";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getAdvertPlace(id).then((response) => {
        const item = response.data;
        this.form = this.__format(item);
        if (this.form.picUrl) {
          this.imageUploader.fileList = [{ url: this.form.picUrl }];
        }
        this.open = true;
        this.title = "修改零售云广告位";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateAdvertPlace(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addAdvertPlace(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除零售云广告位编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delAdvertPlace(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有零售云广告位数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportAdvertPlace(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () {});
    },
  },
};
</script>